<?php 
	header("Content-type: text/html; charset=utf-8");
	require_once('auth_i.inc.php');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=8" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/themes/redmond/jquery-ui-1.8.9.custom.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/ui.multiselect.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/asud.css" />

	<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
	<script src="js/i18n/grid.locale-ru.js" type="text/javascript"></script>
	<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
	<script src="js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>

<script type="text/javascript">

function custom_group_elem( value, options )
{
    var elem = ''
	var chk_val = value.split(',');

	$.ajaxSetup({async: false});

	$.getJSON('req/grp_opt.php', 
		function(data)
		{
			$.each(data, function (key, val)
			{
				if (chk_val.indexOf(val.id) == -1)
					elem += '<input type="checkbox" value="' + val.id + '">&nbsp;' + val.name + '</input><br/>&nbsp;';
				else
					elem += '<input type="checkbox" checked="checked" value="' + val.id + '">&nbsp;' + val.name + '</input><br/>&nbsp;';
			});
			
		}
	);

	return elem;
}

function custom_elem_value(elem, action, val)
{

	var items = '';

	if (action == 'get') // the form has been submitted
	{
    	for (var i in elem)
    	{
        	if (elem[i].tagName == 'INPUT' && elem[i].checked )
            	items += elem[i].value + ',';
      	}

      	items = items.replace(/,$/, '');
   	}
   	else
   	{
		var chk_val = val.split(','); 	

   	  	for (var i in elem)
      	{
        	if (elem[i].tagName == 'INPUT')
         	{
            	if (chk_val.indexOf(elem[i].value) == -1)
               		elem[i].checked = false;
            	else
               		elem[i].checked = true;
         	}
      	}
   }

   return items;
}

function custom_event_elem( value, options )
{
    var elem = ''
	var chk_val = value.split(',');

	$.ajaxSetup({async: false});

	$.getJSON('req/eve_opt.php', 
		function(data)
		{
			$.each(data, function (key, val)
			{
				if (chk_val.indexOf(val.id) == -1)
					elem += '<input type="checkbox" value="' + val.id + '">&nbsp;' + val.name + '</input><br/>&nbsp;';
				else
					elem += '<input type="checkbox" checked="checked" value="' + val.id + '">&nbsp;' + val.name + '</input><br/>&nbsp;';
			});
			
		}
	);

	return elem;
}


$(function() { 
  $("#list").jqGrid({
    url:'req/usr_list.php',
	editurl:'req/usr_edit.php',	
    datatype: 'json',
    mtype: 'GET',
    colNames:['login', 'Имя пользователя','Пароль', 'Еще раз', 'Админ ?','Упр ?','Группы пользователя', 'События пользователя'],
    colModel : [ 
      {name:'u_login', index:'u_login', width:150, editable: true, editoptions:{size:20}, editrules:{required:true, edithidden:true} }, 
      {name:'u_name', index:'u_name', width:185, editable: true, editoptions:{size:20}}, 
	  {name:'password1', hidden: true,  editable: true, edittype:"password", editoptions:{size:20}, editrules:{ edithidden:true} }, 
	  {name:'password2', hidden: true,  editable: true, edittype:"password", editoptions:{size:20}, editrules:{ edithidden:true} },
      {name:'u_p_admin', index:'u_p_admin', width:50, editable: true, edittype:'checkbox',editoptions:{ value:'Да:Нет'} },
      {name:'u_p_edit', index:'u_p_edit', width:50, editable: true, edittype:'checkbox',editoptions:{ value:'Да:Нет'} },

	  {
			name:'group_list',
			index: 'group_list',
			hidden: true,
			editable: true,	
			edittype: 'custom',
			editrules:{ edithidden:true},
			editoptions: { multiple: true, list: "one, two, three", custom_element: custom_group_elem, custom_value: custom_elem_value
			}
      },

	  {
			name:'event_list',
			index: 'event_list',
			hidden: true,
			editable: true,	
			edittype: 'custom',
			editrules:{ edithidden:true},
			editoptions: { multiple: true, list: "one, two, three", custom_element: custom_event_elem, custom_value: custom_elem_value
			}
      }

    ],
    sortname: 'u_login',
    sortorder: 'desc',
    viewrecords: true,
  });

function check_post_data(postdata, formid)
{
	if (postdata.password1 != postdata.password2)
	{
		return [false, "Пароли не совпадают"];
	}

    $status = true;
	$message = '';

	$.ajaxSetup({async: false});

	$.post('req/usr_edit.php', {oper:'check', login: postdata.u_login},
		function (data)
		{
			try
			{
				var msg = $.parseJSON(data);

                if (msg.error != null)
				{
					$status = false;
					$message = msg.error;
				}
			}
			catch (e)
			{
				$status = false;
				$message = 'Ошибка базы данных.';
			}
		});

		return [$status, $message];
}
	

$( "#edit-button" )
			.button()
			.click(function() {
				var gr = jQuery("#list").jqGrid('getGridParam','selrow'); 

				if( gr != null ) 
					jQuery("#list").jqGrid('editGridRow',gr,{reloadAfterSubmit:false,closeAfterEdit:true, 

					beforeShowForm: function(formid)
					{
						$('#tr_u_login').hide();
					},

					beforeSubmit: function(postdata, formid)
					{
						if (postdata.password1 != postdata.password2)
						{
							return [false, "Пароли не совпадают"];
						}

						return [true, ''];
					},
				 }); 

				else 
					alert("Выбирите строку для редактирования !"); 
			});

$( "#add-button" )
			.button()
			.click(function() {
				jQuery("#list").jqGrid('editGridRow',"new",{reloadAfterSubmit:true,closeAfterAdd:true, beforeSubmit: check_post_data }); 
			});


$("#remove-button")
			.button()
			.click(function() { 

				var gr = $("#list").jqGrid('getGridParam','selrow'); 

				if( gr != null ) 
				{
					$("#list").jqGrid('delGridRow',gr,{reloadAfterSubmit:true}); 
				}
				else 
				{
					alert("Выбирите строку для удаления !"); 
				}
			});

}); 

</script>

</head>
<body>
<?php // menu bar
	require_once('menu.inc.php');

	print menu($menu_items, 'user.php');
?>

<div id="main-box">
	<table id="list"></table> 
	<div id="button-box">	
		<button id="add-button">Добавить</button>
		<button id="edit-button">Редактировать</button>
		<button id="remove-button">Удалить</button>
	</div>
</div>

</body>
</html>
